import os
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import urllib.request
chrome_options = Options()
# chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-images')
chrome_options.add_argument('window-size=1920x1080')

# 谷歌浏览器位置
chrome_location = r'D:\chrome-win32\chrome.exe'
# 谷歌浏览器驱动地址
chrome_path = r'D:\chrome-win32\chromedriver.exe'


def get_standard():
    chrome_options.binary_location = chrome_location
    driver = webdriver.Chrome(options=chrome_options)
    driver.maximize_window()
    driver.implicitly_wait(1)  # 隐式等待
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/122.0.6261.95 Safari/537.36',
        'Referer': 'http://www.moe.gov.cn/s78/A07/zcs_ztzl/2017_zt06/17zt06_bznr/bznr_zyjyzyjxbz/'
    }
    print('正在打开链接：http://www.moe.gov.cn/s78/A07/zcs_ztzl/2017_zt06/17zt06_bznr/bznr_zyjyzyjxbz/')
    list_url = f"http://www.moe.gov.cn/s78/A07/zcs_ztzl/2017_zt06/17zt06_bznr/bznr_zyjyzyjxbz/"
    driver.get(list_url)
    time.sleep(2)
    lists = driver.find_elements(By.CSS_SELECTOR, ".moe-list-title-2nd")
    time.sleep(2)
    for item in lists:
        href_value = item.find_element(By.CSS_SELECTOR, "h2 > a").get_attribute("href")
        one_dir = item.find_element(By.CSS_SELECTOR, "h2 > a").text.replace(" >>","")
        time.sleep(2)
        # 执行 JavaScript 代码，在新标签页中打开链接
        js = 'window.open("{0}");'.format(href_value)
        driver.execute_script(js)
        # 获取所有窗口的句柄（handle）列表
        window_handles = driver.window_handles
        # 切换到最后一个窗口（新窗口）
        new_window = window_handles[-1]
        driver.switch_to.window(new_window)
        big_class_items = driver.find_elements(By.CSS_SELECTOR, ".moe-list-title-2nd")
        time.sleep(2)
        for big_class_item in big_class_items:
            big_class_href_value = big_class_item.find_element(By.CSS_SELECTOR, "h2 > a").get_attribute("href")
            two_dir = big_class_item.find_element(By.CSS_SELECTOR, "h2 > a").text.replace(" >>","")
            js = 'window.open("{0}");'.format(big_class_href_value)
            driver.execute_script(js)
            # 获取所有窗口的句柄（handle）列表
            window_handles = driver.window_handles
            # 切换到最后一个窗口（新窗口）
            new_window = window_handles[-1]
            driver.switch_to.window(new_window)
            small_class_items = driver.find_elements(By.CSS_SELECTOR, ".moe-list-title-2nd")
            time.sleep(2)
            for small_class_item in small_class_items:
                big_class_href_value = small_class_item.find_element(By.CSS_SELECTOR, "h2 > a").get_attribute("href")
                three_dir = small_class_item.find_element(By.CSS_SELECTOR, "h2 > a").text.replace(" >>","")
                js = 'window.open("{0}");'.format(big_class_href_value)
                driver.execute_script(js)
                # 获取所有窗口的句柄（handle）列表
                window_handles = driver.window_handles
                # 切换到最后一个窗口（新窗口）
                new_window = window_handles[-1]
                driver.switch_to.window(new_window)
                li_lists = driver.find_elements(By.CSS_SELECTOR, "#list>li")
                for li_item in li_lists:
                    pdf_url = li_item.find_element(By.TAG_NAME, "a").get_attribute("href")
                    pdf_name = li_item.find_element(By.TAG_NAME, "a").get_attribute("title")
                    one_dir_url = "D:\\专业教学标准\\2025\\{0}".format(one_dir)
                    two_dir_url = "D:\\专业教学标准\\2025\\{0}\\{1}".format(one_dir, two_dir)
                    save_url = "D:\\专业教学标准\\2025\\{0}\\{1}\\{2}\\".format(one_dir, two_dir, three_dir)
                    if not os.path.exists(one_dir_url):
                        os.mkdir(one_dir_url)
                    if not os.path.exists(two_dir_url):
                        os.mkdir(two_dir_url)
                    if not os.path.exists(save_url):
                        os.mkdir(save_url)
                    req = urllib.request.Request(pdf_url, headers=headers)
                    file_name = str(save_url) + "{0}.pdf".format(pdf_name)
                    with urllib.request.urlopen(req) as response, open(file_name, 'wb') as out_file:
                        data = response.read()  # 这将读取整个文件
                        out_file.write(data)
                    time.sleep(2)
                    print(str(pdf_name)+"下载完成")
                time.sleep(2)
                driver.close()
                # 获取所有窗口的句柄（handle）列表
                window_handles = driver.window_handles
                # 切换到最后一个窗口（新窗口）
                new_window = window_handles[-1]
                driver.switch_to.window(new_window)
            time.sleep(2)
            driver.close()
            # 获取所有窗口的句柄（handle）列表
            window_handles = driver.window_handles
            driver.switch_to.window(window_handles[-1])
            time.sleep(2)
        time.sleep(2)
        driver.close()
        time.sleep(2)
        # 获取所有窗口的句柄（handle）列表
        window_handles = driver.window_handles
        driver.switch_to.window(window_handles[0])
        time.sleep(2)
    input("输入任意键后停止")


if __name__ == '__main__':
    get_standard()
